<template>
  <div class="container">
    <h1 class="font-weight-100 text-center">我的问卷</h1>
    <!-- 按钮 -->
    <div class="mb-15">
      <el-button type="primary" :icon="Plus" @click="goToEditor">创建问卷</el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="title" label="问卷标题" align="center" />
      <el-table-column prop="surveyCount" label="题目数" width="120" align="center" />
      <el-table-column
        prop="createDate"
        label="创建日期"
        width="200"
        align="center"
        :formatter="formatDate"
      />
      <el-table-column
        prop="updateDate"
        label="最近更新时间"
        width="200"
        align="center"
        :formatter="formatDate"
      />
      <el-table-column fixed="right" label="操作" width="300" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handlePreview(scope.row)">
            查看问卷
          </el-button>
          <el-button link type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-popconfirm title="是否确认删除" @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button link type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

import { deleteSurveyById, getAllSurvey } from '@/db/operation';
import { formatDate } from '@/utils';
import type { SurveyDBData, SurveyDBReturnData } from '@/types';

const router = useRouter();

const tableData = ref<SurveyDBData[]>([]);

const goToEditor = () => {
  router.push('/editor');
};
function getData() {
  getAllSurvey().then((res) => {
    tableData.value = res;
  });
}
getData();

function handlePreview(surveyInfo: SurveyDBReturnData) {
  router.push(`/preview/${surveyInfo.id}`);
}
function handleEdit(surveyInfo: SurveyDBReturnData) {
  router.push(`/editor/${surveyInfo.id}/survey-type`);
}
function handleDelete(surveyInfo: SurveyDBReturnData) {
  deleteSurveyById(surveyInfo.id)
    .then(() => {
      ElMessage.success('删除成功');
      getData();
    })
    .catch(() => {
      ElMessage.error('删除失败');
    });
}
</script>

<style lang="scss" scoped>
.container {
  margin-top: 60px;
  padding: 20px;
}
</style>
